# -*- coding: utf-8 -*-
from Common.yaml_method import YamlMethod
import requests
import json


class SendLarkMessage:
    """
    飞书机器人发送消息
    """

    def __init__(self):
        self.APP_ID = YamlMethod().read_data('lark_key.yaml')['APP_ID']
        self.APP_SECRET = YamlMethod().read_data('lark_key.yaml')['APP_SECRET']

    def get_tenant_access_token(self):
        """
        获取 Tenant Access Token
        :return:
        """
        url = "https://open.feishu.cn/open-apis/auth/v3/tenant_access_token/internal/"
        payload = {
            "app_id": self.APP_ID,
            "app_secret": self.APP_SECRET
        }
        response = requests.post(url, json=payload)
        data = response.json()
        if data.get("code") == 0:
            return data["tenant_access_token"]
        else:
            raise Exception("Failed to get access token: ", data.get("msg"))


    def send_lark_message(self, open_id, title, content, level, severity, create_user):
        """
        向用户发送卡片消息
        :param open_id: 接收者的飞书open_id
        :param title: 卡片标题
        :param content: 缺陷标题
        :param level: 缺陷优先级
        :param severity: 缺陷严重程度
        :param create_user: 缺陷创建人
        :return:
        """
        access_token = self.get_tenant_access_token()
        url = "https://open.feishu.cn/open-apis/im/v1/messages?receive_id_type=open_id"
        headers = {
            "Authorization": f"Bearer {access_token}",
            "Content-Type": "application/json"
        }
        # 构建符合飞书格式的卡片内容
        card_content = {
            "config": {
                "wide_screen_mode": True
            },
            "header": {
                "title": {
                    "tag": "plain_text",
                    "content": title
                },
                "template": "blue"
            },
            "elements": [
                {
                    "tag": "div",
                    "text": {
                        "tag": "lark_md",
                        "content": content
                    }
                },
                {
                    "tag": "div",
                    "text": {
                        "tag": "lark_md",
                        "content": "**优先级：<font color='red'> %s</font>       严重程度：<font color='red'>%s</font>"
                                   "       创建人：<font color='red'>%s</font>**" % (level, severity, create_user)
                    }
                },
                {
                    "tag": "action",
                    "actions": [
                        {
                            "tag": "button",
                            "text": {
                                "tag": "plain_text",
                                "content": "点击查看详情"
                            },
                            "url": "http://tp.micoworld.net/#/bugs/bugs",
                            "type": "primary"
                        }
                    ]
                }
            ]
        }
        # 将卡片内容转为 JSON 字符串
        payload = {
            "receive_id": open_id,
            "msg_type": "interactive",
            "content": json.dumps(card_content)
        }
        response = requests.post(url, headers=headers, json=payload)
        data = response.json()
        if data.get("code") == 0:
            print("Card message sent successfully!")
        else:
            print("Failed to send card message:", data.get("msg"))
            print("Response data:", data)